﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using CodeWork.Library;
using CodeWork.Library.Data;
using log4net;

namespace BDHomePage.BLL
{
    public class LinkSubmission
    {
        public static void SubmitLink(string url)
        {
            try
            {
                // Get the user IP who submitted the url
                string userIp = HttpContext.Current.Request.UserHostAddress;

                // If the user submitted the url in www.domain.com format, 
                // then make it http://www.domain.com fomrat
                if (!url.StartsWith("http://"))
                    url = "http://" + url;

                // Creating the search condition to do a conditional search to 
                // check whether the user ip exists in banned ip list
                CodeWork.DAL.BDHomePage.Banned banned = new CodeWork.DAL.BDHomePage.Banned();
                List<Condition> conditions = new List<Condition>();
                conditions.Add(new Condition("banned_ip", ConditionOperator.Equal, userIp, JoinOperator.FirstValue));

                // If the submitted url matches the url format and if the user ip is not found in 
                // banned ip list then create a submission
                if (RegExUtil.IsUrl(url) && banned.LoadCount(conditions) < 1)
                    CodeWork.DAL.BDHomePage.LinkSubmission.Create(url, userIp);
                else
                    throw new ArgumentException("The URL could not be accepted");
            }
            catch (Exception ex)
            {
                // Setting log information about the exception
                StringBuilder logText = new StringBuilder("New link submission caused server error: Parameters( ");
                logText = logText.Append("url -> ").Append(url);
                logText = logText.Append(" )");

                // Write the log into handled exception list
                ILog log = LogHelper.GetHandledFileLogger("SubmitLink");
                if (log.IsErrorEnabled)
                    log.Error(logText.ToString(), ex);

                // return failure
                throw ex;
            }
        }

        public static Link ApproveLink(int submissionId, string linkUrl, string linkDescription, int linkCategoryId )
        {
            Link link = new Link();
            link.Url = linkUrl;
            link.Description = linkDescription;
            link.Category = new LinkCategory();
            link.AddLink();

            return link;
        }
    }
}
